package com.cyt.work.wb.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.work.wb.dao.WbUserDao;
import com.cyt.work.wb.model.po.WbUser;
import com.cyt.work.wb.model.vo.WbUserVo;
import com.cyt.work.wb.service.WbUserService;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.wx.model.po.WxEducationUser;
import com.cyt.wx.model.po.WxMember;
import com.cyt.wx.model.vo.WxEducationUserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 维保模块_人员信息-人员信息Service层实现类
 *
 * @author shengQiang Yu
 * @date 2019-11-28 15:14:32
 */
@Service("wbUserService")
public class WbUserServiceImpl extends BaseServiceImpl<WbUser> implements WbUserService {

    @Resource
    private WbUserDao wbUserDao;

    @Autowired
    public void setBaseDao(WbUserDao wbUserDao) {
        this.baseDao = wbUserDao;
    }

    /**
     * 分页查询
     *
     * @param wbUserVo 接受参数对象
     * @param pageNum          分页数
     * @param pageSize         每页显示条数
     * @return ReturnResult
     * @author shengQiang Yu
     * @date 2019-11-28 15:14:32
     */
    @Override
    public ReturnResult page(WbUserVo wbUserVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        List<WbUserVo> list = wbUserDao.selectByCondition(wbUserVo);
        PageInfo<WbUserVo> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param wbUserVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author shengQiang Yu
     * @date 2019-11-28 15:14:32
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(WbUserVo wbUserVo, SysUser sysUser) {
        if (StringUtils.isBlank(wbUserVo.getId())) {
            WbUser wbUser = new WbUser(sysUser);
            wbUser.setApplyId(wbUserVo.getApplyId());
            wbUser.setMemberId(wbUserVo.getMemberId());
            wbUser.setName(wbUserVo.getName());
            wbUser.setNum(wbUserVo.getNum());
            wbUser.setType(wbUserVo.getType());
            wbUser.setRole(wbUserVo.getRole());
            wbUser.setPhone(wbUserVo.getPhone());
            wbUser.setPassword(MD5Util.MD5Encode(wbUserVo.getPassword()));
            wbUser.setStatus(wbUserVo.getStatus());
            wbUser.setServicerId(wbUserVo.getServicerId());
            wbUserDao.insert(wbUser);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            WbUser wbUser = wbUserDao.selectByPrimaryKey(wbUserVo.getId());
            wbUser.setApplyId(wbUserVo.getApplyId());
            wbUser.setName(wbUserVo.getName());
            wbUser.setNum(wbUserVo.getNum());
            wbUser.setType(wbUserVo.getType());
            wbUser.setRole(wbUserVo.getRole());
            wbUser.setPhone(wbUserVo.getPhone());
            wbUser.setPassword(MD5Util.MD5Encode(wbUserVo.getPassword()));
            wbUser.setStatus(wbUserVo.getStatus());
            wbUser.setServicerId(wbUserVo.getServicerId());
            wbUser.setUpdateTime(new Date());
            wbUser.setUpdateUser(sysUser.getId());
            wbUserDao.updateByPrimaryKey(wbUser);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param wbUserVo 参数接受对象
     * @param sysUser 当前用户
     * @return ReturnResult
     * @author shengQiang Yu
     * @date 2019-11-28 15:14:32
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(WbUserVo wbUserVo, SysUser sysUser) {
        //要修改的字段
        WbUser wbUser = new WbUser();
        wbUser.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        wbUser.setUpdateUser(sysUser.getId());
        wbUser.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(WbUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wbUserVo.getId())) {
            criteria.andIn("id", Arrays.asList(wbUserVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        wbUserDao.updateByExampleSelective(wbUser, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param wbUserVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author shengQiang Yu
     * @date 2019-11-28 15:14:32
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(WbUserVo wbUserVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(WbUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wbUserVo.getId())) {
            criteria.andIn("id", Arrays.asList(wbUserVo.getId().split(",")));
        }
        wbUserDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 查询对象集合
     *
     * @param wbUserVo 对象
     * @return List 对象集合
     * @author shengQiang yu
     * @date 2019-11-28 16:53
     */
    @Override
    public List<WbUser> listExample(WbUserVo wbUserVo) {
        Example example = new Example(WbUser.class);
        example.setOrderByClause(" create_time desc");
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(wbUserVo.getApplyId())) {
            criteria.andEqualTo("applyId", wbUserVo.getApplyId());
        }
        if (StringUtils.isNotEmpty(wbUserVo.getMemberId())) {
            criteria.andEqualTo("memberId", wbUserVo.getMemberId());
        }
        if (StringUtils.isNotEmpty(wbUserVo.getPhone())) {
            criteria.andEqualTo("phone", wbUserVo.getPhone());
        }
        if (StringUtils.isNotEmpty(wbUserVo.getType())) {
            criteria.andEqualTo("type", wbUserVo.getType());
        }
        if (StringUtils.isNotEmpty(wbUserVo.getServicerId())) {
            criteria.andEqualTo("servicerId", wbUserVo.getServicerId());
        }
        if (StringUtils.isNotEmpty(wbUserVo.getName())) {
            criteria.andLike("name", "%" + wbUserVo.getName() + "%");
        }
        if (StringUtils.isNotEmpty(wbUserVo.getNum())) {
            criteria.andLike("num", "%" + wbUserVo.getNum() + "%");
        }

        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        return wbUserDao.selectByExample(example);
    }
    /**
     * 退出
     *
     * @param userId 会员id
     * @return
     * @author shengQiang yu
     * @date 2019-11-28 16:52
     */
    @Override
    public ReturnResult exit(String userId) {
        WbUser wbUser=this.selectByPrimaryKey(userId);
        if(wbUser!=null){
            wbUser.setMemberId("");
            int num=updateByPrimaryKey(wbUser);
            if(num>0){
                return new ReturnResult("退出成功");
            }
        }
        return new ReturnResult(ErrorCode.CODE_1, "退出失败");
    }
    /**
     * 登录
     *
     * @param wxMember 会员信息
     * @param loginName 登录名
     * @param password 登录密码
     * @param applyId 应用id
     * @return
     * @author shengQiang yu
     * @date 2019-11-28 16:52
     */
    @Override
    public ReturnResult login(WxMember wxMember,String loginName,String password,String applyId) {
        List<WbUser> wbUserList=this.listExample(new WbUserVo(applyId,wxMember.getId()));
        if (CollUtil.isNotEmpty(wbUserList)) {
            // 如果本身绑定，则直接返回成功
            WbUser wbUser = wbUserList.get(0);
            if (StringUtils.equals(wbUser.getPhone(), loginName)) {
                return new ReturnResult(wbUser.getId());
            }
            return new ReturnResult(ErrorCode.CODE_1, "本账号已绑定过，请用正确的账号登录");
        }
        // 查看用户是否存在
        List<WbUser> wbUsers = this.listExample(new WbUserVo(applyId,loginName,""));
        if (CollUtil.isEmpty(wbUsers)) {
            return new ReturnResult(ErrorCode.CODE_1, "未查询到该账号，请联系管理员导入");
        }
        WbUser wbUser = wbUsers.get(0);
        // 不是本账号
        if (StringUtils.isNotEmpty(wbUser.getMemberId()) && !StringUtils.equals(wbUser.getMemberId(), wxMember.getId())) {
            return new ReturnResult(ErrorCode.CODE_1, "该账号已被其他人绑定");
        }
        if (!StringUtils.equals(wbUser.getPassword(), MD5Util.MD5Encode(password))) {
            return new ReturnResult(ErrorCode.CODE_1, "密码不正确");
        }
        wbUser.setMemberId(wxMember.getId());
        this.updateByPrimaryKey(wbUser);
        return new ReturnResult(wbUser.getId());
    }
}